#!/usr/bin/env python3
"""
PaddleOCR图章识别脚本
使用方法: python run_paddle_ocr.py --image_path /path/to/image.jpg
"""

import argparse
import sys
import os
import logging
from pathlib import Path

# 添加src目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'src'))

from seal_recognizer import SealRecognizer

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def main():
    parser = argparse.ArgumentParser(description='PaddleOCR图章识别工具')
    parser.add_argument('--image_path', '-i', required=True, 
                       help='输入图片路径')
    parser.add_argument('--output_dir', '-o', 
                       help='输出目录（可选，默认为图片所在目录）')
    parser.add_argument('--save_debug', action='store_true',
                       help='保存调试图片（红色掩码、预处理图等）')
    
    args = parser.parse_args()
    
    # 检查输入文件
    if not os.path.exists(args.image_path):
        logger.error(f"输入文件不存在: {args.image_path}")
        sys.exit(1)
    
    # 设置输出目录
    if args.output_dir:
        output_dir = Path(args.output_dir)
        output_dir.mkdir(parents=True, exist_ok=True)
    else:
        output_dir = Path(args.image_path).parent
    
    try:
        # 初始化识别器
        logger.info("初始化PaddleOCR识别器...")
        recognizer = SealRecognizer()
        
        # 执行识别
        logger.info(f"开始识别图片: {args.image_path}")
        result = recognizer.recognize(args.image_path)
        
        # 输出结果
        print("\n" + "=" * 60)
        print("PaddleOCR识别结果:")
        print("=" * 60)
        print(result)
        print("=" * 60)
        
        # 保存结果到文件
        result_file = output_dir / f"paddle_result_{Path(args.image_path).stem}.txt"
        with open(result_file, 'w', encoding='utf-8') as f:
            f.write(result)
        logger.info(f"识别结果已保存到: {result_file}")
        
        # 保存调试图片
        if args.save_debug:
            debug_files = [
                "red_mask_debug.jpg",
                "seal_roi_marked.jpg", 
                "seal_preprocessed.jpg"
            ]
            for debug_file in debug_files:
                if os.path.exists(debug_file):
                    debug_dest = output_dir / debug_file
                    os.rename(debug_file, debug_dest)
                    logger.info(f"调试图片已保存: {debug_dest}")
        
    except Exception as e:
        logger.error(f"识别过程出错: {str(e)}", exc_info=True)
        sys.exit(1)


if __name__ == "__main__":
    main()

